package com.ybkj.o2o.zhuanxian.common.config;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.ybkj.o2o.zhuanxian.common.error.Error;
import com.ybkj.o2o.zhuanxian.common.error.ErrorConstantV4;
import com.ybkj.o2o.zhuanxian.common.error.ResultTransport;
import com.ybkj.o2o.zhuanxian.entity.Order;
import javafx.util.Builder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Component
public class DaijiaApi {

    @Value("${spring.daijia_url}")
    private  String DAIJIA_URL;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 预算费用
     */
    private static final String BUDGETED_EXPENXE =
            "api/zhuanxian/wxBudgetedExpense?areaId={areaId}&startLat={startLat}"
                    + "&startLng={startLng}&endLat={endLat}&endLng={endLng}";

    /**
     * 查询是否开起随机红包
     */
    private static final String IS_RANDOM_REDPACKET = "api/zhuanxian/isRandomRedPacket";

    /**
     * 查询是否开起随机红包
     * @param type 结果类型（isRandomRedPacket为判断是否打开开关，cycle获取红包周期）
     * @return
     */
    public Object isRandomRedPacket(String type){
        Gson gson = new Gson();
        String url = buildApi(DAIJIA_URL,IS_RANDOM_REDPACKET);
        String result = restTemplate.getForObject(url, String.class);
        JSONObject resultJson = JSON.parseObject(result);
//        Map<String, Object> resultMap = new HashMap<>();
//        resultMap = gson.fromJson(result, resultMap.getClass());
        Map<String, Object> returnMap = new HashMap<>();
        if("success".equals(resultJson.get("message").toString())){
//            JSONObject data = JSON.parseObject(resultMap.get("data").toString());
            JSONObject data = resultJson.getJSONObject("data");
            returnMap.put("isRandomRedPacket", Boolean.valueOf(data.get("isRandomRedPacket").toString()));
            returnMap.put("cycle", data.getString("cycle"));
            if("isRandomRedPacket".equals(type)){
                return Boolean.valueOf(data.get("isRandomRedPacket").toString());
            } else {
                Map<String,Object> map = new HashMap<>();
                map.put("cycle",data.getString(("cycle")));
                map.put("money",data.getDouble("money"));
                return map;
            }
        } else {
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 接单成功发送短信
     *
     * @param appKey
     */
    public String jiedanSms(String appKey, Order order) {
        StringBuilder builder = new StringBuilder();
        String orderStr = JSONObject.toJSONString(order);
        builder.append(buildApi(DAIJIA_URL, "api/zhuanxian/jiedanSms?appKey={appKey}"));
        Map<String, String> kv = new HashMap<>();
        kv.put("appKey", appKey);

        if (null != order.getId()) {
            builder.append("&orderId={orderId}");
            kv.put("orderId", String.valueOf(order.getId()));
        }
        if (null != order.getEmployId()) {
            builder.append("&employId={employId}");
            kv.put("employId", String.valueOf(order.getEmployId()));
        }
        if (null != order.getEmployName()) {
            builder.append("&employName={employName}");
            kv.put("employName", String.valueOf(order.getEmployName()));
        }
        if (null != order.getPassengerId()) {
            builder.append("&passengerId={passengerId}");
            kv.put("passengerId", String.valueOf(order.getPassengerId()));
        }
        if (null != order.getPassengerPhone()) {
            builder.append("&passengerPhone={passengerPhone}");
            kv.put("passengerPhone", String.valueOf(order.getPassengerPhone()));
        }
        if (null != order.getCompanyId()) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(order.getCompanyId()));
        }
        String result = restTemplate.getForObject(builder.toString(), String.class, kv);
        return result;
    }

    /**
     * 调用代驾预算费用
     *
     * @param server   代驾地址
     * @param areaId   收费ID
     * @param startLat
     * @param startLng
     * @param endLat
     * @param endLng
     * @return
     */
    public JSONObject budgetedExpenseV5(String server, Long areaId, Double startLat, Double startLng, Double endLat, Double endLng) {
        String response = restTemplate.getForObject(buildApi(server, BUDGETED_EXPENXE), String.class, areaId, startLat, startLng, endLat, endLng);
        JSONObject json = null;
        if (null != response) {
            json = JSONObject.parseObject(response);
        }
        return json;
    }

    /**
     * 查询收费标准.
     *
     * @param serverUrl 服务器地址.
     * @param lineId    线路id.
     * @return 收费标准.
     */
    public Map<String, Object> findArea(String serverUrl, Long lineId) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (lineId != null) {
            StringBuilder build = new StringBuilder();
            build.append(buildApi(serverUrl, "api/zhuanxian/getPrice.json?lineId={lineId}"));
            String result = restTemplate.getForObject(build.toString(), String.class, lineId);
            JSONObject jsonObject = JSON.parseObject(result);
            int code = jsonObject.getIntValue("code");

            if (code == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                map.put("jihuoMoney", data.getDouble("jihuoMoney"));
                map.put("baocheMoney", data.getDouble("baocheMoney"));
                map.put("pincheMoney", data.getDouble("pincheMoney"));
            } else {
                map.put("jihuoMoney", 0);
                map.put("baocheMoney", 0);
                map.put("pincheMoney", 0);
            }

        }

        return map;
    }

    /**
     * 构建地址.
     */
    private String buildApi(String server, String api) {
        // www.scezu.com/
        StringBuilder builder = new StringBuilder();

        String daijiaServer = StringUtils.trimToEmpty(server).toLowerCase();
        if (daijiaServer.startsWith("www")) {
            builder.append("https://");
        } else if (!daijiaServer.startsWith("http://") && !daijiaServer.startsWith("https://")) {
            builder.append("http://");
        }

        daijiaServer = daijiaServer.replace("http/", "");

        builder.append(daijiaServer);
        if (!daijiaServer.endsWith("/")) {
            builder.append("/");
        }

        if (StringUtils.isNotBlank(api)) {
            builder.append(api);
        }

        return builder.toString();
    }

    /***
     * 根据乘客逻辑或许该乘客允许的并行下单量
     * @param server
     * @param passengerId
     * @return
     */
    public Long getParallelOrderNumber(String server, Long passengerId) {
        Long num = 0L;
        try {
            Map<String, String> kv = new HashMap<String, String>();
            StringBuilder builder = new StringBuilder();
            builder.append(buildApi(server, "api/passenger/v4/getParallelOrderNumber?passengerId={passengerId}"));
            kv.put("passengerId", String.valueOf(passengerId));
            String result = restTemplate.getForObject(builder.toString(), String.class, kv);
            JSONObject jsonObject = JSON.parseObject(result);
            int code = jsonObject.getIntValue("code");
            if (code == 0) {
                if (null != jsonObject.get("data")) {
                    num = jsonObject.getLongValue("data");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return num;
    }

}
